home *** CD-ROM | disk | FTP | other *** search
- Path: io.UWinnipeg.ca!wsimpson
- From: Bill Simpson <wsimpson@uwinnipeg.ca>
- Newsgroups: comp.lang.c
- Subject: quick decision: is n a power of 2?
- Date: Fri, 19 Jan 1996 12:00:01 -0600
- Organization: The University of Manitoba
- Message-ID: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: io.uwinnipeg.ca
- Mime-Version: 1.0
- Content-Type: TEXT/PLAIN; charset=US-ASCII
-
- Is there a fast way to decide whether a number n is a power of 2?
-
- In my problem
- if ((high-low+1) is a power of 2)
- {
- do one thing
- }
- else
- {
- do another
- }
- e.g. low=0, high=7: 7-0+1 is a power of 2.
-
- The only thing I have thought of is that if n is power of 2
- log(n)/log(2) is an integer
- BUT this is going to be a SLOW computation. Needs to be fast.
-
- Since I am dealing with unsigned long ints, I guess I can just store all
- 31 powers of 2 in a table and compare to n. Though I don't know a fast
- algorithm to compare a number to 31 numbers in an array.
-
- Perhaps there is a tricky nonportable way to see if I have power-of-2 by
- looking at bits? (That is fine for this application)
-
- Thanks very much for any help.
-
- Bill Simpson
-